#!/usr/bin/env python

# Script d'acquisition des Observations provenant
# du module d'acquisition Arduino

# Librairies
import serial
import string
import time
import urllib
import datetime

'''
    ########################################
    Initialization of Connection listening
    ########################################
'''
def initArduinoCon(portUNix="/dev/ttyAMA0"):
    return serial.Serial(portUNix,9600,8,parity='N',stopbits=1,timeout=1)

'''
    ########################################
    Logs Management
    ########################################

    Logs Levels
    0 : no logs
    1 : only in file
    2 : only on screen
    3 : screen & file
'''
def logs(msg):

    LOGS_LVL = 3
    LOGS_HANDLER = 0
    if LOGS_HANDLER==0 and (LOGS_LVL==1 or LOGS_LVL==3):
        filedef = 'logArduino-'+time.strftime("%y_%m_%d",time.localtime())+".log"
        LOGS_HANDLER = open(filedef,"a")

    if LOGS_LVL==1 or LOGS_LVL==3 :
        LOGS_HANDLER.write(msg+"\n")
    
    if LOGS_LVL==2 or LOGS_LVL==3 :
        print msg

'''
    ########################################
    Message analysis & management
    ########################################
'''
def analyzeAndManageMessage(msg):
    msg_init = msg
    msgs = string.split(msg,"|")

    temp=""
    pres=""
    hum=""
    lum=""
    
    for indicateur in msgs:
        if(indicateur[0:2]=="T="):
            temp = indicateur[2:]
            logs("Temperature found => "+temp)
        if(indicateur[0:2]=="P="):
            pres = indicateur[2:]
            logs( "Pression found => "+pres)
        if(indicateur[0:2]=="H="):
            hum = indicateur[2:]
            logs( "Humidity found => "+hum)
        if(indicateur[0:2]=="L="):
            lum = indicateur[2:]
            logs( "Lum. found => "+lum)

    url = "http://192.168.0.5/JCult/index.php?service=newObs&temp="+temp+"&hum="+hum+"&pres="+pres+"&lum="+lum
    logs("HTTP URL : "+url)
    f = urllib.urlopen(url)
    logs("HTTP Response : "+f.read())
    logs("#####################################################")
    
'''
    Partie Principale - Boucle d'écoute
    -----------------------------------
'''
#DTE_BEGIN = datetime.today()

CPT_ITEMS = 1

ArduinoSerial = initArduinoCon("/dev/ttyAMA0")
ArduinoSerial.open()
logs("#####################################################")
# Boucle de traitement - Ecoute des valeurs
try:
    while 1:        
        line = ArduinoSerial.readline()
        if line:
            logsmsg = " Item N°"+str(CPT_ITEMS)
            logs(logsmsg)
            logs("#####################################################")
            logs(time.strftime("%H:%M:%S",time.localtime())+" => Received: "+line)
            analyzeAndManageMessage(line)
            CPT_ITEMS = CPT_ITEMS+1
                            
except KeyboardInterrupt:
    pass # do cleanup here
    ArduinoSerialtest.flush()
    print 'END'
ArduinoSerialtest.close()
